// var actpro_contentsbill = require('../../model/pro_contents')
// var actcart = require('../../sys/cart')
// var actcart = require('../../../../xc/sys/purchaseorder')
var actbill = require('../../../../xc/model/user_warehouse')

var app = getApp();
Component({
  options: {
    addGlobalClass: true,
    multipleSlots: true
  },
  /**
   * 组件的属性列表
   */
  properties: {
     

  },

  /**
   * 组件的初始数据
   */
  data: {
    show: false,
    selected: {

    },
    oneattr: 0,
    uid:-1,
    discount:30
  },
  ready: function () {

  },
  /**
   * 组件的方法列表
   */
  methods: {
    onShow(proid, uid) {
      console.log("app.globalData")
      console.log(app.globalData.configdata.wholesale.warehouse)
      if(app.globalData.configdata && app.globalData.configdata.wholesale && app.globalData.configdata.wholesale.warehouse && app.globalData.configdata.wholesale.warehouse.deposit){
        this.setData({
          discount:app.globalData.configdata.wholesale.warehouse.deposit
        })
        
      }
      this.setData({
        uid:uid
      })
      this.getsaleproinfo(proid, uid)
    },
    confirmselected(e) {
      var dataset = e.currentTarget.dataset;
      // var that = this;
      var selected = this.data.selected;
      // var buytype = dataset.buytype; //1加购 2立即买
      // var objmodel = that.data.objmodel;
      console.log("selected.nums")
      console.log(selected.nums)

      if (selected.nums <= 0) {
        wx.showToast({
          icon: "error",
          title: '请至少选择一件',
        })
        return false
      }

     
        console.log(this.data.objmodel)
        console.log(this.data.selected)

        var obj = this.data.objmodel;
        var attrs = this.data.selected.attrs;
        var arr = ['guigetype','about', 'id', 'name', 'realprice', 'simg', 'skudata', 'skuht', 'unit']
        var newmodel = {}

        for (var i in arr) {
          newmodel[arr[i]] = obj[arr[i]]
        }

        var newattr = {}
        for (var a in attrs) {
          if (attrs[a]['num'] > 0) {
            attrs[a]['uid']=this.data.uid
            newattr[a] = attrs[a]
          }
        }

        newmodel['attrs'] = newattr
        console.log("newmodel")
        app.globalData.depcart["data"] = [newmodel]
        console.log(newmodel)
        // return

        wx.navigateTo({
          url: '/xc_lshop/shop/paycore/depositpay?inquiryuid='+this.data.uid
        })

    },
    //获取仓库商品信息
    getsaleproinfo(proid, uid) {
      var that = this;
      actbill.saleproinfo(proid, uid).then(function (res) {
        if (res['status'] == 1) {
          var obj = res['obj']
          if (obj["guigetype"] != "-1") {
            obj["skuht"] = that.sku(obj["skudata"]);
          }
          var updatemodel={show:true,objmodel:obj}
         

          if (obj["guigetype"] == "-1") {
           console.log("obj")
           console.log(obj)

            var item = {
              stock: obj["stock"],
              weight: obj["weight"],
              realprice: obj["realprice"],
              costomprice: obj["costomprice"],
              num: 1
            }

            var attrs = {
              '-1': item
            }

            updatemodel["selected.attrs"] = attrs;

          } else {


            var attrs = obj['skuht'];
            
            for (var t in attrs) {
               attrs[t]['num'] = 0;
                attrs[t]['key'] = t.split("_")
            }

           console.log("attrs")
           console.log(attrs)

            updatemodel["selected.attrs"] = attrs;
          }
          updatemodel["selected.guigetype"] = obj["guigetype"];
            
          that.setData(updatemodel)
          that.makeprice()
        } else {
          wx.showModal({
            title: '错误',
            content: res['message'],
            complete: (res) => {
              if (res.cancel) {

              }

              if (res.confirm) {

              }
            }
          })
        }
      })
    },
    changeoneattr(e) {
      var dataset = e.currentTarget.dataset;
      var index = dataset.index;
      if (this.data.oneattr != index) {
        this.setData({
          oneattr: index
        })
      }
    },
    makeprice() {
      var totalprice = 0;
      var type = 0;
      var nums = 0;
      var selected = this.data.selected;
      console.log("makeprice")

      console.log(selected)
      if (selected.guigetype == 1) {
        var attrs = selected.attrs;
        for (var i in attrs) {
          if (attrs[i]['num'] >= 1) {
            type += 1;
            nums += attrs[i]['num'];
            totalprice += attrs[i]['realprice'] * attrs[i]['num'] * 100
          }
        }
      } else {
        type = 1;
        nums = selected.attrs['-1'].num
        totalprice += selected.attrs['-1']['realprice'] * selected.attrs['-1']['num']  * 100
  

      }
      console.log("totalprice")
        console.log(totalprice)
      this.setData({
        'selected.totalprice': totalprice,
        'selected.type': type,
        'selected.nums': nums,
      })


    },
    // 更新价格
    updateprice(e){
      var key = e.currentTarget.dataset.key
      var val = e.detail;
      var selected = this.data.selected

      selected['attrs'][key]['realprice'] = val
      this.setData({
        'selected': selected
      })
  
      this.makeprice()
    },
    // 更新数量
    updatenum(e) {
      var key = e.currentTarget.dataset.key
      var val = parseInt(e.detail);
      var selected = this.data.selected

      selected['attrs'][key]['num'] = val
      this.setData({
        'selected': selected
      })
  
      this.makeprice()
    },
    sku(sku) {
      var arrs = [];
      for (var i = 0; i < sku.grouplabel.length; i++) {
        var attr = [];
        for (var n = 0; n < sku.grouplabel[i]["attrs"].length; n++) {
          attr.push(n);
        }
        arrs.push(attr);
      }
      //array.fill(value, start, end)
      var cartesianproduct = Array.prototype.reduce.call(arrs, function (a, b) {
        var ret = [];
        a.forEach(function (a) {
          b.forEach(function (b) {
            ret.push(a.concat([b]));
          });
        });
        return ret;
      }, [
        []
      ]);
      var skuht = {};
      sku.stockdata.forEach(function (val, i) {
        skuht[cartesianproduct[i].join("_")] = {
          index:i,
          stock: parseInt(val["stock"]),
          isshow: val["isshow"],
          weight: val["weight"],
          isdefault: val["isdefault"],
          // salesvolume: val["salesvolume"],
          simg: val["simg"],
          fullsimg: val["fullsimg"],
          price: val["price"],
          realprice: val["realprice"],
          // activityprice: val["activityprice"]
        }
      })
      return skuht;
    },
    onCloseShade(){
      this.setData({
        show:false
      })
    }
  }
  
})